package com.example.demo.service;

import com.example.demo.entity.bean.dataSource1.MemberBean;
import com.example.demo.entity.dataSource2.ESDictEntity;
import com.example.demo.service.dataSource1.impl.MemberService;
import com.example.demo.service.dataSource2.ESDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Wen Gao on 2018/7/11.
 */
@Service
@Transactional(transactionManager = "xatx",propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public class TransactionService {

    @Autowired
    private MemberService memberService;
    @Autowired
    private ESDictService esDictService;

    public void singleTransactionTest() {
        // 剧本:将999999999这条member的name先改为update1,然后故意抛异常,然后再改为update2
        // 如果memberService不开启事务,则执行完数据库中name为update1
        // 如果memberService开启事务,则执行完数据库中name为更新前的原始值
        MemberBean memberBean = memberService.getMemberByMemberUid(999999999);
        memberBean.setName("update1");
        memberService.updateMember(memberBean);
        int a = 1/0; //制造异常
        memberBean.setName("update2");
        memberService.updateMember(memberBean);

    }

    /**
     * 如果不使用Primary数据源,仅仅使用Second数据源,则需要声明使用 secondTransactionManager,否则无法使用事务
     * */
    public void secondTransactionTest() {
        List<ESDictEntity> esDictList = esDictService.getByWord("gaowen");
        if(esDictList != null && esDictList.size()==1) {
            esDictList.get(0).setSource("update1");
            esDictService.update(esDictList.get(0));
        }
        int a = 1/0; // 制造异常
        esDictList.get(0).setSource("update2");
        esDictService.update(esDictList.get(0));
    }

    public void multiTransactionTest() {
        // 剧本:将member999999999 name更新为update1,将es_dict id=1的source改为source_update,然后抛出异常
        //
        MemberBean memberBean = memberService.getMemberByMemberUid(999999999);
        memberBean.setName("update");
        memberService.updateMember(memberBean);
        List<ESDictEntity> esDictList = esDictService.getByWord("gaowen");
        if(esDictList != null && esDictList.size()==1) {
            esDictList.get(0).setSource("update");
            esDictService.update(esDictList.get(0));
        }
        int a = 1/0;
    }
}
